/*
 * Copyright (c) 2025 EasyAdmin
 * All rights reserved.
 *
 * This file is part of the [EasAdmin] project.
 * Unauthorized copying of this file, via any medium, is strictly prohibited.
 * Proprietary and confidential.
 *
 * Author: EasyAdmin ( 1073602@qq.com )
 * Website: https://www.xhxiao.com
 */
package com.easy.app.controller.system;

import com.easy.framework.common.model.R;
import com.easy.framework.common.utils.AssertUtil;
import com.easy.framework.common.utils.Func;
import com.easy.framework.common.utils.Sm2Utils;
import com.easy.framework.common.validate.Add;
import com.easy.framework.common.validate.Update;
import com.easy.framework.database.page.Pagination;
import com.easy.framework.poi.utils.ExcelUtils;
import com.easy.framework.security.model.LoginUser;
import com.easy.framework.security.utils.SecurityUtils;
import com.easy.framework.web.base.BaseController;
import com.easy.framework.common.config.SecretProperties;
import com.easy.module.log.annotation.Log;
import com.easy.module.log.enums.Operation;
import com.easy.module.system.entity.SysRole;
import com.easy.module.system.entity.SysUser;
import com.easy.module.system.query.SysUserQuery;
import com.easy.module.system.service.ISysRoleService;
import com.easy.module.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 用户表 控制器
 *
 * @author EasyAdmin ( 1073602@qq.com )
 * @date 2025-08-19
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    private final ISysUserService sysUserService;

    private final ISysRoleService sysRoleService;

    private final SecretProperties secretProperties;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@perm.hasPermission('system:user$list')")
    @GetMapping("/page")
    public R<Pagination<SysUser>> page(SysUserQuery query) {
        return R.success(sysUserService.page(query, () -> sysUserService.queryList(query)));
    }

    /**
     * 获取用户列表
     */
    @PreAuthorize("@perm.hasPermission('system:user$list')")
    @GetMapping("/list")
    public R<List<SysUser>> list(SysUserQuery query) {
        return R.success(sysUserService.queryList(query));
    }


    @Log(title = "用户管理", type = Operation.EXPORT)
    @PreAuthorize("@perm.hasPermission('system:user$export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUserQuery query) throws IOException {
        List<SysUser> list = sysUserService.queryList(query);
        ExcelUtils.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", type = Operation.IMPORT)
    @PreAuthorize("@perm.hasPermission('system:user$import')")
    @PostMapping("/importData")
    public R importData(MultipartFile file, boolean updateSupport) throws Exception {
        if (!file.isEmpty()) {
            List<SysUser> userList = ExcelUtils.importExcel(file.getInputStream(), SysUser.class);
            System.out.println("User list size:" + userList.size());
        }
        return R.success();
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtils.exportExcel(response, new ArrayList<SysUser>(), "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@perm.hasPermission('system:user$query')")
    @GetMapping("/{userId}")
    public R get(@PathVariable("userId") Long userId) {
        sysUserService.validateDataScope(userId);
        SysUser sysUser = sysUserService.getById(userId);
        sysUser.setRoleIds(sysRoleService.getRoleIdListByUserId(userId));
        return R.success(sysUser);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@perm.hasPermission('system:user$query')")
    @GetMapping("/role/list")
    public R getRoleList(@RequestParam(name = "userId", required = false) Long userId) {
        sysUserService.validateDataScope(userId);
        List<SysRole> roles = sysRoleService.list();
        return R.success(SecurityUtils.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@perm.hasPermission('system:user$add')")
    @Log(title = "用户管理", type = Operation.INSERT)
    @PostMapping
    public R add(@Validated({Add.class}) @RequestBody SysUser user) {
        if (sysUserService.exists(SysUser::getUsername, user.getUsername())) {
            return R.fail("新增用户'" + user.getUsername() + "'失败，登录账号已存在");
        } else if (Func.isNotEmpty(user.getMobile()) && sysUserService.exists(SysUser::getMobile, user.getMobile())) {
            return R.fail("新增用户'" + user.getUsername() + "'失败，手机号码已存在");
        } else if (Func.isNotEmpty(user.getEmail()) && sysUserService.exists(SysUser::getEmail, user.getEmail())) {
            return R.fail("新增用户'" + user.getUsername() + "'失败，邮箱账号已存在");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return R.result(sysUserService.add(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@perm.hasPermission('system:user$edit')")
    @Log(title = "用户管理", type = Operation.UPDATE)
    @PutMapping
    public R edit(@Validated({Update.class}) @RequestBody SysUser user) {
        sysUserService.validateAllowed(user.getId());
        if (sysUserService.exists(SysUser::getUsername, user.getUsername(), SysUser::getId, user.getId())) {
            return R.fail("修改用户'" + user.getUsername() + "'失败，登录账号已存在");
        } else if (Func.isNotEmpty(user.getMobile()) && sysUserService.exists(SysUser::getMobile, user.getMobile(), SysUser::getId, user.getId())) {
            return R.fail("修改用户'" + user.getUsername() + "'失败，手机号码已存在");
        } else if (Func.isNotEmpty(user.getEmail()) && sysUserService.exists(SysUser::getEmail, user.getEmail(), SysUser::getId, user.getId())) {
            return R.fail("修改用户'" + user.getUsername() + "'失败，邮箱账号已存在");
        }
        return R.result(sysUserService.update(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@perm.hasPermission('system:user$remove')")
    @Log(title = "用户管理", type = Operation.DELETE)
    @DeleteMapping("/{userIds}")
    public R remove(@PathVariable("userIds") Long[] userIds) {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId())) {
            return R.fail("当前用户不能删除");
        }
        return R.result(sysUserService.deleteByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@perm.hasPermission('system:user$resetPwd')")
    @Log(title = "用户管理", type = Operation.UPDATE)
    @PutMapping("/resetPwd")
    public R resetPwd(@RequestBody SysUser user) {
        AssertUtil.isNotEmpty(user.getPassword(), "非法访问");
        sysUserService.validateAllowed(user.getId());
        String password = Sm2Utils.decrypt(secretProperties.getPrivateKey(), user.getPassword(), secretProperties.getCharset());
        return R.result(sysUserService.updatePassword(user.getId(), SecurityUtils.encryptPassword(password)));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@perm.hasPermission('system:user$edit')")
    @Log(title = "用户管理", type = Operation.UPDATE)
    @PutMapping("/changeStatus")
    public R changeStatus(@RequestBody SysUser user) {
        sysUserService.validateAllowed(user.getId());
        return R.result(sysUserService.updateStatus(user.getId(), user.getStatus()));
    }

    /**
     * 个人信息
     */
    @GetMapping("profile")
    public R<SysUser> profile() {
        return R.success(sysUserService.getById(SecurityUtils.getUserId()));
    }

    /**
     * 修改个人信息
     */
    @Log(title = "修改个人信息", type = Operation.UPDATE)
    @PutMapping("profile")
    public R updateProfile(@RequestBody SysUser user) {
        LoginUser loginUser = SecurityUtils.getUser();
        user.setUsername(loginUser.getUsername());
        if (Func.isNotEmpty(user.getMobile()) && sysUserService.exists(SysUser::getMobile, user.getMobile(), SysUser::getId, loginUser.getUserId())) {
            return R.fail("修改用户'" + user.getUsername() + "'失败，手机号码已存在");
        }
        if (Func.isNotEmpty(user.getEmail()) && sysUserService.exists(SysUser::getEmail, user.getEmail(), SysUser::getId, loginUser.getUserId())) {
            return R.fail("修改用户'" + user.getUsername() + "'失败，邮箱账号已存在");
        }
        user.setId(loginUser.getUserId());
        user.setPassword(null);
        user.setAvatar(null);
        if (sysUserService.updateById(user)) {
            // 更新缓存用户信息
            return R.success();
        }
        return R.fail("修改个人信息异常，请联系管理员");
    }

    /**
     * 修改个人密码
     */
    @Log(title = "修改个人密码", type = Operation.UPDATE)
    @PutMapping("updatePwd")
    public R updatePwd(String oldPassword, String newPassword) {
        LoginUser loginUser = SecurityUtils.getUser();
        SysUser user = sysUserService.getById(loginUser.getUserId());
        String password = user.getPassword();
        oldPassword = Sm2Utils.decrypt(secretProperties.getPrivateKey(), oldPassword, secretProperties.getCharset());
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return R.fail("修改密码失败，旧密码错误");
        }
        newPassword = Sm2Utils.decrypt(secretProperties.getPrivateKey(), newPassword, secretProperties.getCharset());
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return R.fail("新密码不能与旧密码相同");
        }
        if (sysUserService.updatePassword(loginUser.getUserId(), SecurityUtils.encryptPassword(newPassword))) {
            return R.success();
        }
        return R.fail("修改密码异常，请联系管理员");
    }

    /**
     * 修改个人头像
     */
    @Log(title = "修改个人头像", type = Operation.UPDATE)
    @PostMapping("avatar")
    public R avatar(@RequestParam("avatarUrl") String avatarUrl) throws Exception {
        if (Func.isNotEmpty(avatarUrl)) {
            LoginUser loginUser = SecurityUtils.getUser();
            SysUser sysUser = new SysUser();
            sysUser.setAvatar(avatarUrl);
            sysUser.setId(loginUser.getUserId());
            if (sysUserService.updateById(sysUser)) {
                // 更新缓存用户头像
//                loginUser.setAvatar(avatarUrl);
//                tokenService.setLoginUser(loginUser);
                return R.success();
            }
        }
        return R.fail("上传图片异常，请联系管理员");
    }
}
